package com.shiwaixiangcun.customer.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mobstat.SendStrategyEnum;
import com.baidu.mobstat.StatService;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.HttpParams;
import com.shiwaixiangcun.customer.Common;
import com.shiwaixiangcun.customer.GlobalApi;
import com.shiwaixiangcun.customer.GlobalConfig;
import com.shiwaixiangcun.customer.R;
import com.shiwaixiangcun.customer.base.BaseActivity;
import com.shiwaixiangcun.customer.entity.HousePhoneBean;
import com.shiwaixiangcun.customer.entity.ResponseEntity;
import com.shiwaixiangcun.customer.event.EventUtil;
import com.shiwaixiangcun.customer.event.SimpleEvent;
import com.shiwaixiangcun.customer.module.property.PropertyPaymentActivity;
import com.shiwaixiangcun.customer.network.NetworkHelper;
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr;
import com.shiwaixiangcun.customer.utils.JsonUtil;
import com.shiwaixiangcun.customer.utils.SharePreference;
import com.shiwaixiangcun.customer.utils.Utils;
import com.shiwaixiangcun.customer.widget.ChangeLightImageView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
public class ToResidentCertificationActivity extends BaseActivity implements View.OnClickListener {


    private static final int FROM_RENTING = 0x0011;
    private static final int FROM_PROPERTY = 0x0010;
    private static final int FROM_PAYMENT = 0x0001;
    private static final int REQUEST_TYPE_GET_PHONE = 0X0100;
    private static final int REQUEST_TYPE_ADD_PROPERTY = 0x0101;
    private static final int VALIDATE_PROPERTY = 0x0111;

    private ChangeLightImageView backLeft;
    private String houseId;
    private TextView tvLittlePhone;
    private TextView tvNextPhone;
    private List<HousePhoneBean> mPhoneList;
    private Button btnSubmitOpen;
    private EditText etLittlePhone;
    private RelativeLayout rlSuccessSubmit;
    private Button btnOk;
    private ImageView ivSubmitExpression;
    private TextView tvSubmitSuccsse;
    private TextView tvContent;
    private int nextI = 0;
    private String houseName;

    private TextView mTvTitle;
    private TextView mTvDesc;
    private NetworkHelper mNetworkHelper;

    private boolean addFail = false;
    /**
     * 验证的号码为空
     */
    private boolean numberIsEmpty = false;
    /**
     * 验证成功
     */
    private boolean certificationSuccess = false;

    /**
     * 用于标记从哪个页面进入
     * 对于不同的页面进入处理方式不一致
     */
    private int fromActivity;

    /**
     * 用于标记页面显示的标题
     */
    private String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_resident_certification);
        //        百度统计
        StatService.setLogSenderDelayed(10);
        StatService.setSendLogStrategy(this, SendStrategyEnum.APP_START, 1, false);
        StatService.setSessionTimeOut(30);

        mNetworkHelper = new NetworkHelper(this, getSupportFragmentManager());
        mPhoneList = new ArrayList<>();
        EventUtil.getInstance().register(this);
        initBundleData();
        initViewAndEvent();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventUtil.getInstance().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(SimpleEvent simpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.VALIDATE_NUMBER) {
            return;
        }
        switch (simpleEvent.mEventValue) {
            case REQUEST_TYPE_GET_PHONE:
                ResponseEntity<List<HousePhoneBean>> result = (ResponseEntity<List<HousePhoneBean>>) simpleEvent.getData();
                if (null == result.getData() || result.getData().size() == 0) {
                    numberIsEmpty = true;
                    rlSuccessSubmit.setVisibility(View.VISIBLE);
                    tvSubmitSuccsse.setVisibility(View.GONE);
                    tvContent.setText("该房产还没有预留手机号码\n请到物业中心登记");
                    tvContent.setVisibility(View.VISIBLE);
                } else {
                    mPhoneList.addAll(result.getData());
                    rlSuccessSubmit.setVisibility(View.GONE);
                    tvLittlePhone.setText(mPhoneList.get(0).getPhone());

                }
                break;
            case REQUEST_TYPE_ADD_PROPERTY:
                ResponseEntity responseEntity = (ResponseEntity) simpleEvent.getData();
                switch (responseEntity.getResponseCode()) {
                    case 1001:
                        if (type.equals("add")) {
                            tvContent.setText("恭喜您添加房产成功");
                            tvSubmitSuccsse.setText("添加成功");
                        } else {
                            tvContent.setText("恭喜您认证成功");

                            tvSubmitSuccsse.setText("认证成功");
                        }
                        ivSubmitExpression.setImageResource(R.mipmap.submit_success);
                        AppSharePreferenceMgr.put(this, GlobalConfig.propertyAuth, true);
                        rlSuccessSubmit.setVisibility(View.VISIBLE);
                        btnSubmitOpen.setVisibility(View.GONE);
                        certificationSuccess = true;
                        EventUtil.getInstance().post(new SimpleEvent(SimpleEvent.ADD_PROPERTY, 0x0001));
                        break;
                    case 1002:
                        addFail = true;
                        if (type.equals("add")) {
                            tvSubmitSuccsse.setText("添加失败");
                        } else {
                            tvSubmitSuccsse.setText("添加失败");
                        }
                        tvContent.setText(responseEntity.getMessage());
                        ivSubmitExpression.setImageResource(R.mipmap.submit_success);
                        AppSharePreferenceMgr.put(this, GlobalConfig.propertyAuth, false);
                        rlSuccessSubmit.setVisibility(View.VISIBLE);
                        btnSubmitOpen.setVisibility(View.GONE);
                        certificationSuccess = false;
                        break;
                    default:
                        tvContent.setText(responseEntity.getMessage());
                        ivSubmitExpression.setImageResource(R.mipmap.submit_default);
                        tvSubmitSuccsse.setText("认证失败");
                        AppSharePreferenceMgr.put(this, GlobalConfig.propertyAuth, false);
                        rlSuccessSubmit.setVisibility(View.VISIBLE);
                        btnSubmitOpen.setVisibility(View.GONE);
                        certificationSuccess = false;
                        break;

                }

            default:
                break;
        }
    }

    private void initBundleData() {
        Intent intent = getIntent();
        houseId = String.valueOf(intent.getIntExtra("houseId", 0));
        houseName = intent.getStringExtra("slectHouse");

        type = intent.getStringExtra("type");
        fromActivity = intent.getIntExtra("fromActivity", -1);

    }


    /**
     * 初始化界面
     */
    private void initViewAndEvent() {
        backLeft = findViewById(R.id.back_left);
        tvLittlePhone = findViewById(R.id.tv_little_phone);
        tvNextPhone = findViewById(R.id.tv_next_phone);
        btnSubmitOpen = findViewById(R.id.btn_submit_open);
        etLittlePhone = findViewById(R.id.et_little_phone);
        rlSuccessSubmit = findViewById(R.id.rl_success_submit);
        btnOk = findViewById(R.id.btn_ok);
        ivSubmitExpression = findViewById(R.id.iv_submit_expression);
        tvSubmitSuccsse = findViewById(R.id.tv_submit_succsse);
        tvContent = findViewById(R.id.tv_content);
        mTvTitle = findViewById(R.id.tv_title);
        mTvDesc = findViewById(R.id.tv_desc);
        backLeft.setOnClickListener(this);
        tvNextPhone.setOnClickListener(this);
        btnSubmitOpen.setOnClickListener(this);
        btnOk.setOnClickListener(this);
        switch (type) {
            case "add":
                mTvTitle.setText("添加房产");
                mTvDesc.setVisibility(View.INVISIBLE);
                break;
            case "identification":
                mTvTitle.setText("房屋认证");
                mTvDesc.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }


    /**
     * 初始化数据  先获取当前房产下绑定的电话号码
     */
    private void initData() {


        if (!Utils.isNotEmpty(houseId)) {
            Toast.makeText(mContext, "租房信息不全", Toast.LENGTH_LONG).show();
            return;
        }

        getPropertyNumber();


    }


    /**
     * 获取房产下添加的电话号码
     */
    private void getPropertyNumber() {

        HttpParams httpParams = new HttpParams();
        httpParams.put("houseId", houseId);
        httpParams.put("fields", "phone");
        mNetworkHelper.getRequestWithToken(GlobalApi.INSTANCE.getHousePhone(), true, httpParams,
                new NetworkHelper.NetWorkHelperBack() {
                    @Override
                    public void requestSuccess(@NotNull String json) {
                        Type type = new TypeToken<ResponseEntity<List<HousePhoneBean>>>() {
                        }.getType();
                        ResponseEntity<List<HousePhoneBean>> listResult = JsonUtil.fromJson(json, type);
                        if (null == listResult) {

                            return;
                        }
                        EventUtil.getInstance().post(new SimpleEvent(SimpleEvent.VALIDATE_NUMBER, REQUEST_TYPE_GET_PHONE, listResult));

                    }

                    @Override
                    public void requestFail() {
                        showToastShort("服务器异常");

                    }
                });


    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.back_left:
                switch (fromActivity) {
                    case FROM_PROPERTY:
                        finish();
                        break;
                    case FROM_PAYMENT:
                        Intent intent = new Intent();
                        intent.setClass(mContext, AllToolsActivity.class);
                        startActivity(intent);
                        break;
                    default:
                        finish();
                        break;
                }
                break;
            case R.id.tv_next_phone:
                nextI++;
                if (nextI >= mPhoneList.size()) {
                    nextI = 0;
                }
                if (mPhoneList.size() != 0) {
                    tvLittlePhone.setText(mPhoneList.get(nextI).getPhone());
                }
                break;
            case R.id.btn_submit_open:
                String strPhone = tvLittlePhone.getText().toString().trim() + etLittlePhone.getText().toString().trim();
                if (!Utils.isNotEmpty(etLittlePhone.getText().toString().trim())) {
                    Toast.makeText(this, "请补全电话号码后四位", Toast.LENGTH_LONG).show();
                    return;
                }
                if (Utils.isNotEmpty(houseId)) {
                    addHouse(strPhone);
                } else {
                    Toast.makeText(this, "房产信息错误", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_ok:
                if (numberIsEmpty || addFail) {
                    finish();
                } else {
                    String resident = SharePreference.getStringSpParams(this, Common.ISRESIDENT, Common.SIRESIDENT);
                    if (type.equals("add")) {
                        if (certificationSuccess) {
                            switch (fromActivity) {
                                case FROM_RENTING:
                                case FROM_PROPERTY:
                                    finish();
                                    break;
                                case FROM_PAYMENT:
                                    Intent intent = new Intent();
                                    intent.setClass(mContext, PropertyPaymentActivity.class);
                                    startActivity(intent);
                                    break;
                                default:
                                    finish();
                                    break;
                            }


                        } else {
                            rlSuccessSubmit.setVisibility(View.GONE);
                        }
                    } else {
                        if (resident.equals("torent")) {
//                    Intent intent = new Intent(this,ItoRentActivity.class);
//                    startActivity(intent);
                            finish();
                        } else if (resident.equals("tosell")) {
//                    Intent intent = new Intent(this,ItoSellerActivity.class);
//                    startActivity(intent);
                            finish();
                        } else if (resident.equals("online")) {
//                    Intent intent = new Intent(this,HomeActivity.class);
//                    startActivity(intent);
                            finish();
                        }


                    }
                }
                break;
            default:
                break;
        }

    }

//    /**
//     * 验证电话号码
//     *
//     * @param strPhone
//     */
//    private void validateNumber(String strPhone) {
//
//        HttpParams httpParams = new HttpParams();
//        httpParams.put("houseId", houseId);
//        httpParams.put("phone", strPhone);
//        mNetworkHelper.postRequestWithToken(GlobalApi.INSTANCE.getBindPhone(), true, httpParams,
//                new NetworkHelper.NetWorkHelperBack() {
//                    @Override
//                    public void requestSuccess(@NotNull String json) {
//
//                    }
//
//                    @Override
//                    public void requestFail() {
//
//                    }
//                });
//
//    }

    /**
     * 添加房产
     *
     * @param strPhone
     */
    private void addHouse(String strPhone) {

        HttpParams httpParams = new HttpParams();
        httpParams.put("houseId", houseId);
        httpParams.put("phone", strPhone);
        NetworkHelper networkHelper = new NetworkHelper(mContext, getSupportFragmentManager());
        networkHelper.postRequestWithToken(GlobalApi.INSTANCE.getBindHouse(), true, httpParams,
                new NetworkHelper.NetWorkHelperBack() {
                    @Override
                    public void requestSuccess(@NotNull String json) {
                        ResponseEntity responseEntity = JsonUtil.fromJson(json, ResponseEntity.class);
                        if (responseEntity == null) {
                            return;
                        }
                        EventUtil.getInstance().post(new SimpleEvent(SimpleEvent.VALIDATE_NUMBER, REQUEST_TYPE_ADD_PROPERTY, responseEntity));
                    }

                    @Override
                    public void requestFail() {

                    }
                });

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            switch (fromActivity) {
                case FROM_PROPERTY:
                    finish();
                    break;
                case FROM_PAYMENT:
                    Intent intent = new Intent();
                    intent.setClass(mContext, AllToolsActivity.class);
                    startActivity(intent);
                    break;
                default:
                    finish();
                    break;
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        StatService.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        StatService.onPause(this);
    }
}
